package com.guaoran.interview.in2018.collection.map;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author gucheng
 * @Description
 *  LinkedHashMap 有序集合
 *      todo https://segmentfault.com/a/1190000012964859
 *  HashMap.Node ：实现 implements Map.Entry<K,V>
 *  LinkedHashMap.Entry ：继承 extends HashMap.Node<K,V>
 *  HashMap.TreeNode : 继承 extends LinkedHashMap.Entry<K,V>
 * 2019-03-18 9:30
 */
public class LinkedHashMapDemo {
//    public static void main(String[] args) {
//        Map<String,Integer> notSortMap = new HashMap<>();
//        Map<String,Integer> sortMap = new LinkedHashMap<>();
//        for (int i = 0; i < 10; i++) {
//            notSortMap.put(i+"key"+i,i);
//            sortMap.put(i+"key"+i,i);
//        }
//        for (Map.Entry entry : notSortMap.entrySet()) {
//            System.out.println(entry.getKey()+"->"+entry.getValue());
//        }
//        System.out.println("============================");
//        for (Map.Entry entry : sortMap.entrySet()) {
//            System.out.println(entry.getKey()+"->"+entry.getValue());
//        }
//    }



    /*
    LinkedHashMap 集成 HashMap ,在entry 中，新增了 before 和 after ，使得可以有序
    static class Entry<K,V> extends HashMap.Node<K,V> {
        LinkedHashMap.Entry<K,V> before, after;
        Entry(int hash, K key, V value, HashMap.Node<K,V> next) {
            super(hash, key, value, next);
        }
    }
     */
    public static void main(String[] args) {
//        Map<String,Integer> sortMap = new LinkedHashMap<>(16,0.75f,true);
        Map<String,Integer> sortMap = new LinkedHashMap<String,Integer>(16,0.75f,true);
        for (int i = 0; i < 10; i++) {
           sortMap.put("key"+i,i);
        }
        sortMap.entrySet().forEach(m ->{
            System.out.println(m.getKey()+" -> "+m.getValue());
        });
        System.out.println(sortMap.get("key9"));
        System.out.println(sortMap.get("key5"));
        System.out.println(sortMap.get("key3"));

        sortMap.entrySet().forEach(m ->{
            System.out.println(m.getKey()+" -> "+m.getValue());
        });
        System.out.println("=================");
        for (int i = 10; i < 20; i++) {
            sortMap.put("key"+i,i);
        }
        sortMap.entrySet().forEach(m ->{
            System.out.println(m.getKey()+" -> "+m.getValue());
        });
    }
}
